package edu.cmu.fithub.controller;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import java.text.ParseException;
import java.util.List;

import javax.servlet.ServletContextEvent;

import org.hibernate.Session;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.QuartzSchedule;
import edu.cmu.fithub.db.bean.User;

import static org.quartz.JobBuilder.*;

public class InitListener implements javax.servlet.ServletContextListener {
	
	static Scheduler scheduler;
	
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}
	
	public static Scheduler getScheduler() { 
		return scheduler;
	}
	
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		// Retrieve list of scheduled jobs
		Session dbSession = DBHelper.getSessionFactory().openSession();
		List<QuartzSchedule> list = dbSession.createCriteria(QuartzSchedule.class).list();
		if (list.size() == 0) {
			return; // no scheduled workouts
		}
		try {
			SchedulerFactory sf = new StdSchedulerFactory();
			scheduler = sf.getScheduler();
			
			for(QuartzSchedule qSchedule : list) {
				JobDetail job = newJob(WorkoutMailJob.class).withIdentity(
						qSchedule.getScheduleId()+"", "group_j").usingJobData("email", qSchedule.getEmailAddress())
						.usingJobData("body", qSchedule.getEmailMessage()).build();
				CronTrigger trigger = newTrigger()
					.withIdentity(qSchedule.getScheduleId()+ "trigger", "group_j")
					.withSchedule(cronSchedule(qSchedule.getSchedule())).forJob(job)
					.build();
				scheduler.scheduleJob(job, trigger);
				
			}
			scheduler.start();
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
